package smcms.service.cloudstore.service.impl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import smcms.commons.api.entity.result.CommonsResult;
import smcms.service.cloudstore.entity.CloudStoreFileResp;
import smcms.service.cloudstore.mapper.FileManagerMapper;
import smcms.service.cloudstore.service.FileManagerService;

import java.io.File;
import java.io.IOException;

@Service
public class FileManagerServiceImpl implements FileManagerService {
    @Autowired private CommonsResult commonsResult;
    @Autowired
    private FileManagerMapper fileManagerMapper;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Value("${document.path}")
    private String filePath;
    @Override
    public CommonsResult uploadFile(MultipartFile file, String fileType, String operator) {
        if (file.isEmpty()) {
            return commonsResult.failed("上传文件不能为空！");
        }
        //获取后缀
        int index=file.getOriginalFilename().indexOf(".");
        String suffix=file.getOriginalFilename().substring(index);
        String path = "";
        if (!".png".equals(suffix)&&!".jpeg".equals(suffix)&&!".jpg".equals(suffix)) {
            return commonsResult.failed("上传图片必须是png、jpeg、jpg格式");
        }
        try {
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(),
                    file.getSize(), suffix, null);
            CloudStoreFileResp cloudStoreFileResp = new CloudStoreFileResp();
            cloudStoreFileResp.setFileName(storePath.getFullPath());
            cloudStoreFileResp.setFileType(fileType);
            cloudStoreFileResp.setOperatorName(operator);
            fileManagerMapper.saveUpload(cloudStoreFileResp);
            path = storePath.getFullPath();
        } catch (IOException e) {
            return commonsResult.failed("文件上传失败！IO异常");
        }

        return commonsResult.success(path);
    }
}
